package cfca.seal.web.service;

import cfca.seal.bean.AdminUser;
import cfca.seal.bean.SealImage;
import cfca.seal.common.Page;
import cfca.seal.dao.main.ISealImageDao;
import cfca.seal.exception.CodeException;
import cfca.seal.util.ImageUtil;
import cfca.seal.util.OutPicture;
import cfca.seal.util.OutPictureOfDoubleCricle;
import cfca.seal.web.vo.AutoSealModelVo;
import cfca.seal.web.vo.DoubleCircleModelVo;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class SealModelService
{

  @Resource
  private ISealImageDao dao;

  public SealImage getSealModelById(String id)
    throws Exception
  {
    return this.dao.getSealModelById(id);
  }

  public Page getSealModels(SealImage sealImage, String pageNo, AdminUser manager) throws Exception {
    return this.dao.getPage(sealImage, pageNo, manager.getUserType() > 0 ? manager.getOrganizationId() : "");
  }

  public boolean deleteById(String deleteid) throws Exception {
    return this.dao.deleteById(deleteid);
  }

  public boolean update(SealImage model) throws Exception {
    return this.dao.update(model);
  }

  public boolean addSealModel(SealImage model) throws Exception {
    SealImage sealImage = this.dao.getSealModelByModelCode(model.getCode());
    if (sealImage != null)
      throw new CodeException("C3078", "印模编码已经存在");
    return this.dao.insert(model);
  }

  private byte[] createRectangle(AutoSealModelVo sealModelVo) throws CodeException {
    return OutPicture.getRectanglePngToByte(sealModelVo);
  }

  private byte[] createSquare(AutoSealModelVo sealModelVo) throws CodeException {
    return OutPicture.getSquarePngToByte(sealModelVo);
  }

  private byte[] createCircle(AutoSealModelVo sealModelVo) {
    return ImageUtil.transferAlpha(OutPicture.getCirclePngToByte(sealModelVo));
  }

  public byte[] createDoubleCircle(DoubleCircleModelVo sealModelVo) {
    byte[] image = "".getBytes();

    if (0 == sealModelVo.getSealType())
      image = ImageUtil.transferAlpha(OutPictureOfDoubleCricle.getCirclePngToByte(sealModelVo));
    else if (3 == sealModelVo.getSealType()) {
      image = ImageUtil.transferAlpha(OutPictureOfDoubleCricle.getDoubleCirclePngToByte(sealModelVo));
    }
    return image;
  }

  public byte[] createImage(AutoSealModelVo sealModelVo) throws CodeException {
    byte[] image = "".getBytes();
    if (sealModelVo.getSealType() == 0)
      image = createCircle(sealModelVo);
    else if (sealModelVo.getSealType() == 1)
      image = createSquare(sealModelVo);
    else if (sealModelVo.getSealType() == 2) {
      image = createRectangle(sealModelVo);
    }
    return image;
  }

  public int getCountByOrganizationId(String organizationId) throws Exception {
    return this.dao.getCountByOrganizationId(organizationId);
  }
}